<!--
 * @Author: Liz.Zheng
 * @Date: 2021-12-27 11:03:25
 * @LastEditTime: 2023-02-16 10:32:04
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 收支流水
 * @Motto: Write the code. Change the world.
-->
<template>
  <section class="turnover-list">

    <!-- 统计模块 -->
    <section class="" :class="isTenant ? 'border' : ''">

      <div class="staticis">
        <div
            style=" position: absolute;  right: 20px;">
          <a-dropdown>
            <template #overlay>
              <a-menu @click="handleMenuClick">
                <a-menu-item key="1" v-if="!isTenant"
                             v-permission="['streamList', 'auth', 'billStreamRefund']"
                             @click="handleRefundConfig">
                  流水退款配置
                </a-menu-item>
                <a-menu-item key="2" @click="matchRules"
                             v-permission="['streamList', 'auth', 'streamAutoMatchRules']"
                >
                  自动匹配规则
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              更多
              <DownOutlined/>
            </a-button>
          </a-dropdown>
        </div>

        <a-row
            type="flex"
            justify="space-around"
            align="middle"
            :style="{ height: $store.getters.isMobile ? undefined : '80px' }"
            :gutter="[12, 12]"
        >
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-statistic :value="sticsData.sum_amount">
              <template #title>
                <span>总发生额</span>
                <span>（{{ sticsData.sum_total || 0 }}笔）</span>
                <a-tooltip>
                  <template #title>
                    <span>仅包含开启状态下的流水</span>
                  </template>
                  <question-circle-outlined class="mr-5"/>
                </a-tooltip>
                <span><RightCircleOutlined
                    style="color: #5d7ceb; cursor: pointer"
                    @click="sumTotalClick"
                /></span>
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-statistic :value="sticsData.all_match_amount">
              <template #title>
                <span>完全匹配</span>
                <span>（{{ sticsData.all_match_total || 0 }}笔）</span>
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-statistic :value="sticsData.part_match_amount">
              <template #title>
                <span>部分匹配</span>
                <span>（{{ sticsData.part_match_total || 0 }}笔）</span>
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4" style="position: relative">
            <a-statistic :value="sticsData.no_match_amount">
              <template #title>
                <span>未匹配</span>
                <span>（{{ sticsData.no_match_total }}笔）</span>
              </template>
            </a-statistic>

          </a-col>
        </a-row>

      </div>
    </section>

    <!-- 筛选栏 -->
    <section
        class="staticis"
        :class="isTenant ? 'border' : ''"
        style="margin: 10px 0; padding: 15px"
    >
      <a-form layout="vertical">
        <a-row :gutter="[32, 32]" :wrap="true" align="bottom">
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="借贷标">
              <a-select
                  ref="select"
                  v-model:value="formState.loan_type"
                  :options="loanTypeList"
                  class="form-width"
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="汇款方式">
              <a-select
                  ref="select"
                  v-model:value="formState.remit_type"
                  :options="remitTypeList"
                  class="form-width"
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="流水账户">
              <a-select
                  ref="select"
                  v-model:value="formState.account_id"
                  class="form-width"
                  :options="accountList"
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="匹配状态">
              <a-select
                  ref="select"
                  v-model:value="formState.match_status"
                  class="form-width"
                  :options="matchStatusList"
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="单位/房号">
              <a-input
                  v-model:value="formState.keywords"
                  :placeholder="
                  isTenant ? '请输入租客单位名称' : '请搜索对方单位名称、房号'
                "
                  class="form-width"
                  allowClear
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="创建人员">
              <a-select
                  v-model:value="formState.cuser_uid"
                  show-search
                  placeholder="请选择"
                  class="form-width"
                  :options="cuserOptions"
                  allowClear
                  optionFilterProp="label"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="入账时间">
              <a-range-picker
                  v-model:value="formState.incomeDate"
                  :ranges="incomeRanges"
                  :placeholder="['入账起始时间', '入账结束时间']"
                  class="form-width"
                  valueFormat="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="创建时间">
              <a-range-picker
                  v-model:value="formState.createDate"
                  :ranges="createRanges"
                  :placeholder="['创建起始时间', '创建结束时间']"
                  valueFormat="YYYY-MM-DD"
                  class="form-width"
              />
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="发生额">
              <a-row align="middle">
                <a-col style="width: 47%">
                  <a-input-number
                      v-model:value="formState.min_amount"
                      placeholder="起数"
                      :min="0"
                      style="width: 100%"
                  />
                </a-col>
                <a-col style="width: 5%; text-align: center">~</a-col>
                <a-col style="width: 47%">
                  <a-input-number
                      v-model:value="formState.max_amount"
                      placeholder="至数"
                      :min="0"
                      style="width: 100%"
                  />
                </a-col>
              </a-row>
            </a-form-item>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-form-item label="状态">
              <a-select
                  ref="select"
                  v-model:value="formState.close_status"
                  class="form-width"
                  :options="runningList"
              />
            </a-form-item>
          </a-col>
          <a-col>
            <a-space>
              <a-button type="primary" @click="searchClick">确定</a-button>
              <a-button @click="resetClick">重置</a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </section>

    <!-- 表格 -->
    <BillTurnoverTable
        :dataList="dataList"
        :loading="loading"
        :pagination="pagination"
        @showDraweres="showDraweres"
        @addTurnover="addTurnover"
        @importBillFlow="importBillFlow"
        @downLoadClick="downLoadClick"
        @ownerPreStore="ownerPreStore"
        @handleTableChange="handleTableChange"
    />

    <!--  新建收支流水  -->
    <AddBillTurnoverDrawer
        :visible="addDrawer"
        :turnoverDetail="turnoverDetail"
        :ownerId="owner_id"
        @handleClose="handleAddClose"
        @handleSuccess="saveAddTurnover"
    />

    <!-- 明细详情 -->
    <sumTotalModal
        :visible="sumTotalVisible"
        :turnoverDetail="turnoverDetail"
        :isTenant="isTenant"
        @onClose="sumTotalVisible = false"
    />

    <!--  流水退款配置  -->
    <RefundConfigModal
        :visible="refundVisible"
        @handleSettingSuccess="handleRefundCancel"
        @handleCancel="handleRefundCancel"
    />

    <!-- 导出表格 -->
    <ExportComponents
        v-if="isExport"
        :visible="isExport"
        :title="titles"
        :url="isTenant ? '/owner/ownerStreamList' : '/bill/streamList'"
        service="/org"
        method="get"
        :params="paramses"
        :limit="1000"
        :columnstitle="listHanders"
        :custom_result="array"
        :custom_data="true"
        @customDataFunc="customResult"
        @request="$utils.commonRequest"
        @cancel="changeexport"
    />

  </section>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  reactive,
  onActivated,
  toRefs,
  defineAsyncComponent,
  watch,
} from "vue";
import {
  PlusOutlined,
  DownloadOutlined,
  UploadOutlined,
  RightCircleOutlined,
  DownOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import {useRouter} from "vue-router";
import moment from "moment";
import {message} from "ant-design-vue";
import TurnoverDetail from "@/views/bill/TurnoverDetail/index.vue";
import NewTurnover from "@/views/bill/NewTurnover/index.vue";

import sumTotalModal from "./modules/sumTotalModal.vue";
import store from "../../../store";
import BillTurnoverTable from "@/views/bill/BillTurnover/modules/BillTurnoverTable.vue";
import _ from "lodash";
import {xlsx} from "../../../common/utils/xlsx";
import utils from "../../../common/utils/utils";
import AddBillTurnoverDrawer from "@/views/bill/BillTurnover/modules/AddBillTurnoverDrawer.vue";
import RefundConfigModal from '@/views/bill/BillTurnover/modules/RefundConfigModal.vue'
import {ExportComponents} from "bl-common-vue3";
import dayjs, {Dayjs} from "dayjs";

const incomeRanges = {
  今天: [moment(), moment()],
  昨天: [moment().subtract(1, "days"), moment().subtract(1, "days")],
  本周: [moment().startOf("week"), moment().endOf("week")],
  本月: [moment().startOf("month"), moment().endOf("month")],
  上月: [
    moment().subtract(1, "months").startOf("month"),
    moment(moment().subtract(1, "months").startOf("month")).endOf("month"),
  ],
  本年: [moment().startOf("year"), moment().endOf("year")],
};
const createRanges = {
  今天: [moment(), moment()],
  昨天: [moment().subtract(1, "days"), moment().subtract(1, "days")],
  本周: [moment().startOf("week"), moment().endOf("week")],
  本月: [moment().startOf("month"), moment().endOf("month")],
  上月: [
    moment().subtract(1, "months").startOf("month"),
    moment(moment().subtract(1, "months").startOf("month")).endOf("month"),
  ],
  本年: [moment().startOf("year"), moment().endOf("year")],
};

export default defineComponent({
  name: "streamList",
  components: {
    RefundConfigModal,
    QuestionCircleOutlined,
    PlusOutlined,
    DownloadOutlined,
    TurnoverDetail,
    NewTurnover,
    UploadOutlined,
    RightCircleOutlined,
    sumTotalModal,
    BillTurnoverTable,
    AddBillTurnoverDrawer,
    DownOutlined,
    ExportComponents,
  },
  props: {
    turnoverDetail: {
      type: Object,
      default: () => ({}),
    },
    turnoverType: {
      type: String,
      default: "",
    },
    owner_id: {
      type: [Number, String],
      default: 0,
    },
  },
  setup(props) {
    const $router = useRouter();
    const {turnoverDetail, turnoverType} = toRefs(props);
    const isTenant = turnoverType.value === "tenant";
    const addDrawer = ref(false);
    const incomeDate = ref([]);

    /**
     * @description:  table
     */
    const state = reactive({
      refundVisible: false,

    })

    // 筛选
    const formState = reactive({
      loan_type: "",
      remit_type: "",
      account_id: "",
      match_status: "",
      keywords: "",
      cuser_uid: undefined,
      incomeDate: [],
      createDate: [],
      min_amount: "",
      max_amount: "",
      close_status: "",
    });

    const confirmSearchValue = ref({});

    //借贷标
    const loanTypeList = ref([]);

    // 汇款方式
    const remitTypeList = ref([]);

    // 流水账户
    const accountList = ref([]);

    // 匹配状态
    const matchStatusList = ref([
      {
        value: "",
        label: "全部",
      },
      {
        value: "1",
        label: "完全匹配",
      },
      {
        value: "2",
        label: "未匹配",
      },
      {
        value: "3",
        label: "部分匹配",
      },
    ]);

    // 状态
    const runningList = ref([
      {
        value: "",
        label: "全部",
      },
      {
        value: "0",
        label: "关闭",
      },
      {
        value: "1",
        label: "开启",
      },
      {
        value: "2",
        label: "待审核",
      },
      {
        value: "3",
        label: "已驳回",
      },
    ]);

    // 创建人员
    const cuserOptions = ref([]);

    const page = ref(1);
    const limit = ref(20);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const sort = ref("");
    const order = ref("");
    const handleTableChange = (pager, filters, sorter) => {
      dataList.value = [];
      if (sorter) {
        if (sorter.order) {
          sort.value = sorter.order == "ascend" ? "asc" : "desc";
          order.value = sorter.field;
        } else {
          order.value = "";
          sort.value = "";
        }
      }
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableData(formState);
    };
    const dataList = ref([]);
    const getTableData = (searchValue) => {
      loading.value = true;
      return new Promise((resolve) => {
        let url = isTenant ? "/owner/ownerStreamList" : "/bill/streamList";
        let params = {
          page: isExport.value ? 1 : page.value,
          limit: isExport.value ? 100000 : limit.value,
          sort: sort.value,
          order: order.value,
          ...searchValue,
        };

        if (isTenant) {
          // 租客流水
          params.village_id = turnoverDetail.value.village_id;
          // params.build_id = turnoverDetail.value.build_id;
          params.room_id = turnoverDetail.value.id;
          delete params.sort;
          delete params.order;

          if (props.owner_id) {
            delete params.village_id;
            delete params.room_id;
            params.owner_id = props.owner_id;
          }
        }
        paramses.value = {...params};
        request
            .get("/org", url, {...params})
            .then((res) => {
              res.list.forEach((item) => {
                item.build_bind = Array.isArray(item.build_bind)
                    ? null
                    : item.build_bind;
              });
              resolve(res.list);
              dataList.value = res.list;
              total.value = res.total;
            })
            .finally(() => {
              loading.value = false;
            });
      });
    };

    // 搜索
    const searchClick = () => {
      if (formState.createDate && formState.createDate.length > 0) {
        formState.create_start = formState.createDate[0];
        formState.create_end = formState.createDate[1];
      } else {
        formState.create_start = undefined;
        formState.create_end = undefined;
      }
      if (formState.incomeDate && formState.incomeDate.length > 0) {
        formState.income_start = formState.incomeDate[0];
        formState.income_end = formState.incomeDate[1];
      } else {
        formState.income_start = undefined;
        formState.income_end = undefined;
      }
      page.value = 1;
      limit.value = 20;
      confirmSearchValue.value = _.cloneDeep(formState);
      getTableData(confirmSearchValue.value);
    };
    const resetClick = () => {
      for (let key in formState) {
        formState[key] = "";
      }
      formState.cuser_uid = undefined;
      formState.incomeDate = [];
      formState.createDate = [];
      page.value = 1;
      limit.value = 20;
      confirmSearchValue.value = {};
      getTableData(confirmSearchValue.value);
    };

    const addTurnover = () => {
      addDrawer.value = true;
      // $router.push({ name: "newTurnover" });
    };

    const ownerPreStore = () => {
      $router.push({name: "OwnerPreStore"});
    };

    const sticsData = ref({});
    const getStatisticsData = () => {
      if (isTenant) {
        let params = {
          village_id: turnoverDetail.value.village_id,
          // build_id: turnoverDetail.value.build_id,
          room_id: turnoverDetail.value.id,
        };

        if (props.owner_id) {
          delete params.village_id;
          delete params.room_id;
          params.owner_id = props.owner_id;
        }

        request
            .get("/org", "/owner/streamStatistics", {
              ...params,
            })
            .then((res) => {
              sticsData.value = res.data;
            });
      } else {
        request.get("/org", "/bill/streamStatistics").then((res) => {
          sticsData.value = res.data;
        });
      }
    };

    // 明细
    const sumTotalVisible = ref(false);
    const sumTotalClick = () => {
      sumTotalVisible.value = true;
    };

    // 导出报表
    let timer = null;
    const titles = computed(() => {
      return "收支流水列表" + dayjs().format("YYYY-MM-DD-HH:mm:ss");
    });
    const isExport = ref(false);
    const paramses = ref({});
    const listHanders = ref({});
    const array = ref([]);
    const downLoadClick = (data) => {
      const {column, stream_ids} = data
      listHanders.value = column.reduce((obj, v) => {
        obj[v.dataIndex] = v.title;
        return obj;
      }, {});

      paramses.value = {stream_ids: stream_ids, ...formState}
      isExport.value = true;
    };

    const customResult = (ExportList) => {
      ExportList.forEach((item) => {
        item.amount = Number(item.amount);
        item.amount = Number(item.amount);
        item.match_price = Number(item.match_price);
        item.nomatch_price = Number(item.nomatch_price);
        switch (item.is_close) {
          case 0:
            item.is_close = "关闭";
            break;
          case 1:
            item.is_close = "开启";
            break;
          case 2:
            item.is_close = "审批中";
            break;
          case 3:
            item.is_close = "拒绝";
            break;
        }
        if (!item.build_bind) {
          item.room_number_txt = "--";
        } else {
          if (
              Object.keys(item?.build_bind).length &&
              item?.build_bind &&
              item?.build_bind.room.length > 0
          ) {
            let roomtext = [];
            item?.build_bind?.room.forEach((room) => {
              roomtext.push(
                  (room?.build_name || room?.extra?.build_name) +
                  "-" +
                  room.layer_name +
                  "-" +
                  room.room_name
              );
            });
            item.room_number_txt = roomtext.join(",");
          }
        }
      });
      array.value = ExportList;
    };

    const changeexport = () => {
      isExport.value = false;
      message.success("导出成功,请等待文件生成");
    };

    const init = () => {
      getStatisticsData();
      getTableData(confirmSearchValue.value);
      store.dispatch("BillInit").then((data) => {
        remitTypeList.value = data.remit_money;
        remitTypeList.value.unshift({
          label: "全部",
          value: "",
        });
        loanTypeList.value = data.loan_type;
        loanTypeList.value.unshift({
          label: "全部",
          value: "",
        });

        request
            .get("/org", "/bill/getAccountList", {
              buildIds: undefined,
            })
            .then((res) => {
              accountList.value = res.list.map((item) => ({
                value: item.id,
                label: item.name,
              }));
              accountList.value.unshift({
                label: "全部",
                value: "",
              });
            });
        request.get("/org", "/contract/listSearchInit").then((res) => {
          cuserOptions.value = res.data.followup.map((item) => {
            return {
              label: item.realname,
              value: item.uid,
            };
          });
        });
      });
    };
    if (isTenant) {
      init();
    }
    onActivated(() => {
      if (isTenant) return;
      init();
    });

    const importBillFlow = () => {
      $router.push({name: "importBillFlow"});
    };

    const showDraweres = () => {
      getTableData(confirmSearchValue.value);
    };

    const handleAddClose = () => {
      addDrawer.value = false;
    };

    const saveAddTurnover = () => {
      handleAddClose();
      init();
    };

    watch(
        () => props.owner_id,
        () => {
          getStatisticsData();
          resetClick();
        }
    );

    // 流水退款配置
    const handleRefundConfig = () => {
      state.refundVisible = true;
    };

    const handleRefundCancel = () => {
      state.refundVisible = false;
    };

    const matchRules = () => {
      $router.push({name: "matchingRules"})
    }

    return {
      dataList,
      pagination,
      loading,
      sticsData,
      incomeDate,
      incomeRanges,
      createRanges,
      addDrawer,
      isTenant,
      handleTableChange,
      addTurnover,
      downLoadClick,
      ownerPreStore,
      init,
      importBillFlow,
      saveAddTurnover,

      formState,
      remitTypeList,
      accountList,
      sumTotalClick,
      sumTotalVisible,
      loanTypeList,
      matchStatusList,
      cuserOptions,
      searchClick,
      resetClick,
      showDraweres,
      runningList,
      handleAddClose,
      handleRefundConfig,
      handleRefundCancel,
      ...toRefs(state),
      matchRules,
      isExport,
      paramses,
      listHanders,
      array,
      customResult,
      changeexport,
      titles,
    };
  },
});
</script>

<style lang="less" scoped>
.turnover-list {
  padding: 10px;

  .table-header {
    margin: 0 20px;
    color: rgba(0, 0, 0, 0.8);
  }

  .staticis {
    position: relative;
    background: #fff;
    width: 100%;
    padding: 10px;
  }

  .form-width {
    width: 100%;
  }
}

.border {
  border: 1px solid #f0f0f0;
}

:deep(.ant-form-item) {
  margin-bottom: 0;
}
</style>
